<template>
  <div ref="linkRef" :class="[ns.b(), isActive && ns.m('active')]">
    <a :class="ns.e('title')" :style="style" :href="href" @click.prevent="onClick">{{ title }}</a>
    <slot />
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRef, inject, provide, onBeforeUnmount, ref } from 'vue'
import { remove } from '@vue/shared'
import { computedEager } from '@vueuse/core'

import useNamespace from '../_util/hooks/useNameSpace'
import { AnchorContextKey, AnchorLiinkContextKey } from './context'

const preCls = 'x-anchor-link'

export default defineComponent({
  name: preCls,
  props: {
    href: String,
    title: String
  },
  setup(props) {
    const ns = useNamespace(preCls)
    const linkRef = ref()

    const anchorContext = inject(AnchorContextKey)
    const anchorLiinkContext = inject(AnchorLiinkContextKey, undefined)

    const indent = anchorLiinkContext?.indent ? anchorLiinkContext?.indent + 1 : 1
    const isActive = computedEager(() => anchorContext.value.value == props.href)

    const state = reactive({
      el: linkRef,
      href: toRef(props, 'href'),
      indent
    })

    provide(AnchorLiinkContextKey, state)

    anchorContext.links.push(state)
    onBeforeUnmount(() => {
      remove(anchorContext.links, state)
    })

    function onClick() {
      // anhorContext.value.value = props.href
      anchorContext.setActive(props.href)
    }

    return {
      ns,
      linkRef,
      indent,
      style: `padding-left: ${indent * 16}px`,
      isActive,
      onClick
    }
  }
})
</script>
